package com.yhx.security.changyou;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.*;
/**
 * @Description: 签名工具类
 * @date 2020/2/25 11:36
 */
public class SignUtil {
    public static void main(String[] args) throws Exception {


        Map<String,Object> signMap = new HashMap<>(16);
        signMap.put("channelSource","02004362");
        signMap.put("partnerId","S1000131");
        signMap.put("storeId","best_store1");
        signMap.put("outTokenId","15000846203_out");
        signMap.put("mobile","15000846395");
        String signKey="123456789";
        String str=createSign(signMap,signKey);
        System.out.println(str);

    }
    public static String createSign(Map<String,Object> map,String signkey) {
        SortedMap<String, Object> parameters = new TreeMap<>();
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            parameters.put(entry.getValue().toString(),entry.getValue());
        }
        parameters.put(signkey, signkey);
        Iterator<Map.Entry<String, Object>> it = parameters.entrySet().iterator();//所有参与传参的参数按照 accsii 排序（升序）
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            if (null == entry.getKey()) {
                continue;
            }
            Object v = entry.getValue();
            //空值不传递，不参与签名组串
            if (v!= null && StringUtils.isNotBlank((String)v)) {
                sb.append((String)v);
            }
        }
        String result = sb.toString();
        //排序后的字符串
        System.out.println("sha1Hex，待签名字符串:{}"+result);
        return DigestUtils.sha1Hex(result.getBytes(StandardCharsets.UTF_8));
    }


}
